package com.xiaocai.myblog.common;

import com.xiaocai.myblog.enums.ErrorCodeEnum;
import com.xiaocai.myblog.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author chenhefu
 * @date 2019-10-01 03:12
 */
@ControllerAdvice
public class DefaultExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseData handlerError(HttpServletRequest req, Exception  ex )
    {
        logger.error("DefaultExceptionHandler", ex);
        ResponseData d = new ResponseData();
        if (ex instanceof IllegalArgumentException) {
            d.setCode(ErrorCodeEnum.SERVER_ERROR_PARAM.getCode());
            d.setMsg(ex.getMessage());
            logger.warn("DefaultExceptionHandler param error", ex);
            return d;
        }
        d.setCode(ErrorCodeEnum.SERVER_ERROR.getCode());
        d.setMsg(ErrorCodeEnum.SERVER_ERROR.getMsg());
        return d;
    }

    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResponseData handlerError(HttpServletRequest req, BusinessException  ex )
    {
        logger.warn("DefaultExceptionHandler-BusinessException", ex);
        ResponseData d = new ResponseData();
        d.setCode(ErrorCodeEnum.SERVER_ERROR.getCode());
        d.setMsg(ex.getMsg());
        return d;
    }

}
